﻿namespace SchoolSystem.Server.Controllers
{
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using SchoolSystem.Data;
    using SchoolSystem.Server.Repositories;

    public class BaseApiController<T> : ApiController where T : class 
    {
        protected readonly IRepository<T> data;
        protected static Random rand = new Random();
        private DbContext context;

        public BaseApiController()
        {
            this.context = new SchoolSystemEntities();
            this.data = new EfRepostory<T>(context);
        }

        public BaseApiController(IRepository<T> data)
        {
            this.data = data;
        }

        protected T ExecuteOperationAndHandleExceptions<T>(Func<T> operation)
        {
            try
            {
                return operation();
            }
            catch (InvalidOperationException ex)
            {
                var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
                throw new HttpResponseException(errResponse);
            }
            catch (Exception ex)
            {
                var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
                throw new HttpResponseException(errResponse);
            }
        }

        protected Account GetAccountByAccessToken(string accessToken)
        {
            IRepository<Account> accountsData = new EfRepostory<Account>(this.context);

            var account = accountsData.All().AsQueryable().FirstOrDefault(a => a.AccessToken == accessToken);

            if (account == null)
            {
                throw new InvalidOperationException("Invalid user credentials");
            }

            return account;
        }
    }
}